<template>
    <div class="body usersetting TimePicker">
        <div class="my p setting" v-if="userInfo">
            <div class="content">
                <div class="list7">
                    <div class="myorder he p">
                        <div class="content30">
                            <div class="order">
                                <div class="fl">
                                    <span>头像</span>
                                    <span class="bridh"></span>
                                </div>
                                <div class="fr">
                                    <!--<a href="">-->
                                    <div
                                        class="hendicon"
                                        @click="changeImgClick()"
                                    >
                                        <span></span>
                                        <form
                                            id="head_pic"
                                            method="post"
                                            enctype="multipart/form-data"
                                        >
                                            <label
                                                class="file"
                                                style="cursor: pointer"
                                            >
                                                <div
                                                    class="around"
                                                    id="fileList"
                                                >
                                                    <img
                                                        :src="userInfo.head_pic"
                                                    />
                                                    <input
                                                        type="file"
                                                        accept="image/*"
                                                        name="head_pic"
                                                        ref="filElem"
                                                        @change="
                                                            handleFiles($event)
                                                        "
                                                        style="display: none"
                                                    />
                                                </div>
                                            </label>
                                        </form>
                                    </div>
                                    <!--</a>-->
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="myorder p">
                        <div class="content30">
                            <a>
                                <div class="order">
                                    <div class="fl">
                                        <span>用户名</span>
                                    </div>
                                    <div class="fr">
                                        <span>{{ userInfo.nickname }}</span>
                                        <i
                                            class="Mright"
                                            style="background: none"
                                        ></i>
                                    </div>
                                </div>
                            </a>
                        </div>
                    </div>
                    <div class="myorder p">
                        <div class="content30">
                            <a>
                                <div class="order">
                                    <div class="fl">
                                        <span>手机</span>
                                    </div>
                                    <div class="fr">
                                        <span>{{ userInfo.mobile }}</span>
                                        <i
                                            class="Mright"
                                            style="background: none"
                                        ></i>
                                    </div>
                                </div>
                            </a>
                        </div>
                    </div>
                    <div class="sex newinfoli">
                        <van-field
                            readonly
                            clickable
                            name="picker"
                            :value="valuesex"
                            label="性别"
                            placeholder="点击选择性别"
                            @click="showPicker = true"
                        />
                        <van-popup v-model="showPicker" position="bottom">
                            <van-picker
                                show-toolbar
                                :columns="columns"
                                @confirm="onConfirm"
                                @cancel="showPicker = false"
                                item-height="1.3rem"
                                visible-item-count="10"
                            />
                        </van-popup>
                    </div>
                    <div class="birth newinfoli">
                        <van-field
                            readonly
                            clickable
                            name="picker"
                            :value="valuedata + ''"
                            label="生日"
                            placeholder="点击选择生日"
                            @click="showPickerdata = true"
                        />
                        <van-popup v-model="showPickerdata" position="bottom">
                            <van-datetime-picker
                                v-model="currentDate"
                                type="date"
                                title="选择年月日"
                                :min-date="minDate"
                                :max-date="maxDate"
                                @confirm="onConfirmdata"
                                @cancel="showPickerdata = false"
                                item-height="1.3rem"
                                visible-item-count="10"
                            />
                        </van-popup>
                    </div>

                    <div class="myorder p bo">
                        <div class="content30">
                            <a>
                                <div class="order jhemail">
                                    <div class="fl">
                                        <span>邮箱</span>
                                    </div>
                                    <div class="fr">
                                        <input
                                            type="text"
                                            name="mobile"
                                            autocomplete="off"
                                            placeholder="请输入邮箱"
                                            v-model="userInfo.email"
                                        />
                                    </div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
                <div class="close">
                    <a
                        id="asubmit"
                        style="display: none"
                        href="javascript:;"
                        onclick="javascript:$('#head_pic').submit();"
                        >保存头像</a
                    >
                </div>
            </div>
        </div>

        <div class="j_newbutton">
            <div class="j_newbtn" @click="submitUserinfo">提交</div>
        </div>
        <van-overlay :show="allImglength" @click="allImglength = false">
            <van-loading color="#fff" size="1.3rem"
                >图片上传中。。。</van-loading
            >
        </van-overlay>

        <div class="zhanwei"></div>
    </div>
</template>

<script>
import { axiosPost, axiosPostnotoken } from '../../axios';
window.URL = window.URL || window.webkitURL;
import { Toast } from 'vant';
export default {
    name: '',
    data() {
        return {
            allImglength: false,
            userInfo: {},
            filesImg: '',
            formData: new FormData(),

            valuesex: '',
            valuedata: '',
            columns: ['男', '女'],
            showPicker: false,
            showPickerdata: false,
            minDate: new Date(1960, 0, 1),
            maxDate: new Date(),
            currentDate: new Date(),

            filesImgUpload: '',
        };
    },
    computed: {},
    mounted() {
        this.getUserinfo();
    },
    methods: {
        // 提交用户信息
        submitUserinfo() {
            this.userInfo.sex = this.valuesex == '男' ? 0 : 1;
            this.userInfo.head_pic = this.filesImgUpload;
            this.userInfo.birthday = this.valuedata;
            axiosPost('/api/user/editinfo', this.userInfo, (res) => {
                // console.log(res);
                Toast({
                    message: res.msg,
                    duration: 2000,
                });
                if (res.status != 1) {
                    return;
                }
                this.getUserinfo();
                setTimeout(() => {
                    this.$router.go(-1);
                }, 1000);
            });
        },
        // 性别选择
        onConfirm(value) {
            this.valuesex = value;
            this.showPicker = false;
        },
        // 生日选择
        onConfirmdata(value) {
            const add0 = (m) => {
                return m < 10 ? '0' + m : m;
            };
            const time = new Date(value);
            const y = time.getFullYear();
            const m = time.getMonth() + 1;
            const d = time.getDate();
            this.valuedata = y + '-' + add0(m) + '-' + add0(d);
            this.showPickerdata = false;
        },
        // 获取用户信息
        getUserinfo() {
            axiosPost('/api/user/info', {}, (res) => {
                // console.log(res);
                this.userInfo = res.data.user;

                // 设置时间
                if (this.userInfo.birthday != 0) {
                    const add0 = (m) => {
                        return m < 10 ? '0' + m : m;
                    };
                    const time = new Date(
                        Number(String(this.userInfo.birthday) + '000')
                    );
                    const y = time.getFullYear();
                    const m = time.getMonth() + 1;
                    const d = time.getDate();
                    this.valuedata = y + '-' + add0(m) + '-' + add0(d);
                    this.currentDate = time;
                }
                // 设置性别

                this.valuesex = this.userInfo.sex == 0 ? '男' : '女';

                // 设置头像
                if (
                    this.userInfo.head_pic ==
                        '/public/images/icon_goods_thumb_empty_300.png' ||
                    !this.userInfo.head_pic
                ) {
                    this.userInfo.head_pic = require('../../assets/images/user68.jpg');
                } else {
                    this.filesImgUpload = this.userInfo.head_pic;
                }
            });
        },
        // 读取图片并压缩
        readFile(inputFile) {
            let that = this;
            if (inputFile) {
                if (
                    inputFile.type !== 'image/jpeg' &&
                    inputFile.type !== 'image/png' &&
                    inputFile.type !== 'image/gif'
                ) {
                    return Toast({
                        message: '不是有效的图片文件！',
                        duration: 1000,
                    });
                }

                const reader = new FileReader();
                reader.readAsDataURL(inputFile);
                reader.onload = function () {
                    let img = new Image();
                    img.src = this.result;
                    var width = 750, //图像大小
                        height = 1000, //图像大小
                        quality = 1, //图像质量
                        canvas = document.createElement('canvas'),
                        drawer = canvas.getContext('2d');
                    img.onload = function () {
                        const originHeight = img.height;
                        const originWidth = img.width;
                        let compressedWidth = img.height;
                        let compressedHeight = img.width;
                        if (originWidth > width && originHeight > height) {
                            // 更宽更高，
                            if (originHeight / originWidth > height / width) {
                                // 更加严重的高窄型，确定最大高，压缩宽度
                                compressedHeight = height;
                                compressedWidth =
                                    height * (originWidth / originHeight);
                            } else {
                                //更加严重的矮宽型, 确定最大宽，压缩高度
                                compressedWidth = width;
                                compressedHeight =
                                    width * (originHeight / originWidth);
                            }
                        } else if (
                            originWidth > width &&
                            originHeight <= height
                        ) {
                            // 更宽，但比较矮，以width作为基准
                            compressedWidth = width;
                            compressedHeight =
                                width * (originHeight / originWidth);
                        } else if (
                            originWidth <= width &&
                            originHeight > height
                        ) {
                            // 比较窄，但很高，取maxHight为基准
                            compressedHeight = height;
                            compressedWidth =
                                height * (originWidth / originHeight);
                        } else {
                            // 符合宽高限制，不做压缩
                        }
                        canvas.width = compressedWidth;
                        canvas.height = compressedHeight;
                        drawer.drawImage(
                            img,
                            0,
                            0,
                            canvas.width,
                            canvas.height
                        );
                        that.changeimg(canvas.toDataURL('image/jpg', quality));
                        that.$refs.filElem.value = '';
                    };
                };
            } else {
                return;
            }
        },
        changeImgClick() {
            this.$refs.filElem.dispatchEvent(new MouseEvent('click'));
        },
        //换取图片
        changeimg(url) {
            axiosPostnotoken(
                '/api/upload/base64',
                {
                    image: url,
                },
                (res) => {
                    if (res.status != 1) {
                        return Toast({
                            message: res.msg,
                            duration: 1000,
                        });
                    }
                    // console.log(res);
                    this.$nextTick(() => {
                        this.userInfo.head_pic = res.data.src;
                        this.filesImg = res.data.src;
                        this.filesImgUpload = res.data.src;
                    });
                    this.allImglength = false;
                }
            );
        },
        // 上传头像接口
        handleFiles(e) {
            let files = e.target.files;
            this.readFile(files[0]);
            this.allImglength = true;
        },
    },
};
</script>
<style lang="less" src="../../assets/css/timePicker.less" scope></style>
<style lang="less" scope>
.usersetting {
    .van-cell__value {
        position: relative;
        overflow: hidden;
        color: #969799;
        text-align: right;
        vertical-align: middle;
        word-wrap: break-word;
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }
    .jhemail {
        .fr {
            float: right;
        }

        input {
            height: 1.89867rem;
            outline: none;
            width: 9.81333rem;
            padding: 0 0.21333rem;
            font-size: 0.59733rem;
            border: 0;
            padding-right: 0.5546rem;
            text-align: right;
        }
    }

    .list7 .myorder .fr i {
        margin-top: 0.73rem !important;
    }

    .my {
        width: 15.1467rem;
        margin: 0.4267rem auto 0;
        border-radius: 0.4267rem;
    }

    .myorder a {
        color: #232326;
    }

    .logout {
        width: 15.1467rem;
        margin: 0 auto 3rem;
        border-radius: 0.4267rem;
        height: 2.13333rem;
        line-height: 2.13333rem;
        display: block;
        background: #ffffff;
        font-size: 0.59733rem;
        font-weight: 400;
        color: #000000;
        text-align: center;
        cursor: pointer;
    }

    .myorder .order {
        overflow: hidden;
        border-bottom: 0;
    }

    /*  */
    .newinfoli {
        overflow: hidden;
        .van-cell {
            padding: 0 0.427rem;
            height: 2.13333rem;
            line-height: 2.13333rem;
        }
        .van-field__label {
            font-size: 0.59733rem;
            margin-right: auto;
            font-weight: normal;
            width: auto;
            margin-left: 0.21333rem;
            color: #232326;
        }
        .van-cell--borderless::after,
        .van-cell:last-child::after {
            display: block;
        }
        .van-cell::after {
            position: absolute;
            box-sizing: border-box;
            content: ' ';
            pointer-events: none;
            right: 0.427rem;
            bottom: 0.768rem;
            left: auto;
            border: 0;
            -webkit-transform: none;
            transform: none;
            background-image: url('../../assets/images/yr.png');
            background-repeat: no-repeat;
            background-size: cover;
            width: 0.34133rem;
            height: 0.59733rem;
            display: block;
            float: left;
        }
        .van-field__control {
            display: block;
            box-sizing: border-box;
            width: 100%;
            min-width: 0;
            margin: 0;
            padding: 0;
            line-height: inherit;
            text-align: left;
            background-color: transparent;
            border: 0;
            resize: none;
            font-size: 0.59733rem;
            color: #1f1f1f;
            text-align: right;
            padding-right: 0.5546rem;
        }
    }
}
</style>
